<template>
  <div class="inventory-edit-form">
    <!-- 盘点基本信息 -->
    <div class="section">
      <h2 class="section-title">修改抽检单</h2>
      <el-form ref="ruleFormRef" style="max-width:1200px;margin:20px" :model="samp_order" status-icon :rules="rules"
        label-width="auto">
        <el-form-item label="抽检单号" prop="samp_code">
          <el-input v-model="samp_order.samp_code" readonly />
        </el-form-item>

        <div style="display:flex;justify-content:space-between;">
          <!-- 左侧 -->
          <div style="width:48%;">
            <el-form-item label="抽检类型" prop="samp_type" style="margin-bottom:30px;">
              <el-select v-model="samp_order.samp_type" placeholder="请选择盘点类型" @change="handleSelectType">
                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                  :value="item.dict_value" />
              </el-select>
            </el-form-item>

            <el-form-item label="抽检仓库" prop="warehouse_code" style="margin-bottom:30px;">
              <el-select :disabled="true" v-model="samp_order.warehouse_code" placeholder="请选择盘点仓库"
                @change="handleWarehouseChange">
                <el-option v-for="item in warehouses" :key="item.warehouse_code" :label="item.warehouse_name"
                  :value="item.warehouse_code" />
              </el-select>
            </el-form-item>
          </div>

          <!-- 右侧 -->
          <div style="width:48%;">
            <el-form-item label="抽检日期" prop="samp_startdate" style="margin-bottom:30px;">
              <el-date-picker v-model="samp_order.samp_startdate" type="datetime" placeholder="选择日期时间"
                style="width:100%;" />
            </el-form-item>

            <el-form-item label="抽检员" prop="samp_inspector" style="margin-bottom:30px;">
              <el-input v-model="samp_order.samp_inspector" placeholder="请输入盘点员" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 盘点产品明细 -->
    <div class="section">
      <h2 class="section-title">抽检产品明细</h2>
      <div style="float:left;margin:10px 0;">
        <el-button type="primary" @click="productAdd">添加</el-button>
        <el-button @click="productDel">移除</el-button>
      </div>

      <el-table :data="selectedData" border style="width:100%" :cell-style="{textAlign:'center'}"
        :header-cell-style="{textAlign:'center',background:'#f5f7fa',fontWeight:'bold',position:'sticky',top:0}"
        ref="selectedTable" @selection-change="handleSelectedChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="stock_name" label="货品名称" fixed="left" width="150" />
        <el-table-column prop="pro_code" label="货品编号" width="150" />
        <el-table-column prop="pro_brand" label="品牌" width="143" />
        <el-table-column prop="stock_model" label="规格型号" width="125" />
        <el-table-column label="单位" width="70"><template #default="scope">{{ measureValue(scope.row.dict_code)
            }}</template></el-table-column>
        <el-table-column prop="stock_numder" label="当前库存" width="100" />

        <!-- 盘点数量 -->
        <el-table-column label="抽检数量" width="141">
          <template #default="scope"><el-input v-model.number="scope.row.samp_numder" style="width:75px"
              :min="0" /></template>
        </el-table-column>

        <!-- 合格数量 -->
        <el-table-column label="合格数量" width="145">
          <template #default="scope"><el-input v-model.number="scope.row.prodInfo_totnum_qify" style="width:75px"
              :max="scope.row.samp_numder" @input="calcResult(scope.row)" /></template>
        </el-table-column>

        <!-- 不合格数量 -->
        <el-table-column label="不合格数量" width="143">
          <template #default="scope">{{ (scope.row.samp_numder || 0) - (scope.row.prodInfo_totnum_qify || 0)
            }}</template>
        </el-table-column>

        <!-- 盘点结果 -->

      </el-table>

      <!-- 合计 -->
      <div style="height:40px;line-height:40px;">
        <div style="float:left;">合计</div>
        <div style="float:right">
          盘点总数量：{{ sampling_total_qty }} &nbsp;
          合格总数：{{ qualified_total_qty }} &nbsp;
          不合格总数：{{ unqualified_total_qty }}
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="handleUpdate">保存修改</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </div>

    <!-- 产品选择弹窗 -->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
      <div style="margin:10px 0;">
          <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productcode" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号/名称" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
        <div style="float:right;">
          <el-button @click="productReset">重置</el-button>
          <el-button type="primary" @click="productSearch">查询</el-button>
        </div>
      </div>

      <el-table ref="multipleTableRef" :data="productData" :cell-style="{textAlign:'center'}"
        :header-cell-style="{textAlign:'center',background:'#f5f7fa',fontWeight:'bold',position:'sticky',top:0}"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="isDisabled" />
        <el-table-column property="pro_code" label="货品编号" width="180" />
        <el-table-column property="stock_name" label="货品名称" width="200" />
        <el-table-column property="stock_model" label="规格型号" />
        <el-table-column label="单位"><template #default="scope">{{ measureValue(scope.row.dict_code)
            }}</template></el-table-column>
        <el-table-column property="pro_cost_price" label="成本价" />
        <el-table-column property="pro_sale_price" label="销售价" />
        <el-table-column property="stock_numder" label="当前库存" />
      </el-table>
      <br>
      <div style="text-align: center;display: flex; justify-content: center;">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5,10,20,50]"
          background layout="total,sizes,prev,pager,next,jumper" :total="pageCount" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
      <hr>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>

import { ref, reactive, onMounted, watch, computed } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWarehouseStore } from '@/storejs/warehouseStore'

const router = useRouter()
const warehouseStore = useWarehouseStore()
const samp_code = ref(warehouseStore.samp_code || '') // 从仓库 store 取盘点单号

//抽检类型
const options = ref([])


const warehouses   = ref([])  // 仓库列表
const measureOptios = ref([]) // 计量单位字典


let sampAdd = {
  samp_id: 0,
  samp_type: '',            // 盘点类型
  samp_code: '',            // 盘点单号（只读）
  samp_inspector: localStorage.getItem('userLName'), 
  samp_startdate: '',       // 盘点日期
  warehouse_code: '',       // 盘点仓库编码
  warehouse_name: '',       // 盘点仓库名称
  Samp_results: '',         // 1-合格 2-不合格 3-部分合格 4-严重缺陷
  update_by: localStorage.getItem('userLName'),
  update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
  del_flag: '0'
}
const samp_order = reactive({ ...sampAdd })


const ruleFormRef = ref(null)
const rules = reactive({
  warehouse_code: [{ required: true, message: '请选择盘点仓库', trigger: 'change' }],
  samp_type:       [{ required: true, message: '请选择盘点类型', trigger: 'change' }],
  samp_startdate:  [{ required: true, message: '请选择盘点日期', trigger: 'change' }],
  samp_inspector:  [{ required: true, message: '请输入盘点员', trigger: 'blur' }]
})


const dialogTableVisible = ref(false)
const productData   = ref([])   // 可选产品列表
const currentPage   = ref(1)
const pageSize      = ref(5)
const pageCount     = ref(0)
const productcode   = ref('')   // 搜索关键字
const dict_code     = ref('0')  // 单位筛选

const multipleTableRef = ref(null)
const selectedProducts = ref([]) // 临时勾选
const selectedTable    = ref(null)
const selectedRows     = ref([]) // 明细勾选行
const selectedData     = ref([]) // 最终明细
  

const sampling_total_qty = ref(0) // 设置盘点总数量
const qualified_total_qty = ref(0) // 设置合格数量
const unqualified_total_qty = ref(0)

// 只监听 selectedData 的变化，并添加 deep: true 深度监听
watch(selectedData, () => {
  let newSamplingTotal = 0
  let newQualifiedTotal = 0
  let newUnqualifiedTotal = 0

  selectedData.value.forEach(row => {
    // 检查合格数量是否大于抽检数量
    if (row.prodInfo_totnum_qify > row.samp_numder) {
      ElMessage.warning(`${row.stock_name}的合格数量不能大于抽检数量`)
      row.prodInfo_totnum_qify = row.samp_numder
    }

    // 检查抽检数量是否大于库存数量
    if (row.samp_numder > row.stock_numder) {
      ElMessage.warning(`${row.stock_name}的抽检数量不能大于当前库存`)
      row.samp_numder = row.stock_numder
    }

    // 累加计算各项总数
    newSamplingTotal += Number(row.samp_numder || 0)
    newQualifiedTotal += Number(row.prodInfo_totnum_qify || 0)
  })

  // 计算不合格总数
  newUnqualifiedTotal = newSamplingTotal - newQualifiedTotal

  // 一次性更新所有ref值
  sampling_total_qty.value = newSamplingTotal
  qualified_total_qty.value = newQualifiedTotal
  unqualified_total_qty.value = newUnqualifiedTotal
}, { deep: true }) // 深度监听数组内对象变化



// 加载
async function loadEditData() {

    axios.get("http://localhost:5181/api/Inv_Samp/Inv_samp_SelectCode", {
        params: {
            samp_code: samp_code.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
      const main = res.data[0]

        // 填充主表数据
        Object.assign(samp_order, {
            samp_id: main.samp_id,
            samp_code: main.samp_code,
            samp_type: main.samp_type,
            samp_inspector: main.samp_inspector,
            samp_startdate: main.samp_startdate,
            warehouse_code: main.warehouse_code,
            warehouse_name: main.warehouse_name,
          Samp_results: main.Samp_results,
            samp_is_stored: main.samp_is_stored
        })
        // 加载产品明细
        loadProductDetails();

      productCount();
    }).catch((res) => {
        console.log(res)
        ElMessage.error("加载盘点单数据失败");
    })
}

// 加载产品明细数据
function loadProductDetails() {
  axios.get("http://localhost:5181/api/Inv_Samp/Inv_samp_SelectDetail", {
        params: {
      samp_code: samp_code.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then(async (result) => {
        const tempData = [];

        for (const item of result.data) {
            // 获取当前产品的库存
            const stockNumber = await StockSelect(
              samp_order.warehouse_code,
              item.pro_code
            );

            tempData.push({
                ...item,
              stock_numder: stockNumber, // 后续可补充实时库存
              samp_numder: item.samp_numder,
              prodInfo_totnum_qify: item.prodInfo_totnum_qify,
              dict_code: item.unitmeas_id,
              stock_name: item.pro_name,
              stock_model: item.pro_model,

            });
        }
        selectedData.value = tempData;
    }).catch((error) => {
        console.error("加载产品明细失败:", error);
        ElMessage.error('加载产品明细失败');
    });
}

//响应判断逻辑--结果 prodInfo_Sampling_results
function calcResult() {
 
  const total = sampling_total_qty.value;
  const qualify = qualified_total_qty.value;

  if (qualify === total) {
    samp_order.Samp_results = '1'; // 全部合格
  } else if (qualify === 0) {
    samp_order.Samp_results = '2'; // 全部不合格
  } else if (qualify > 0 && qualify < total) {
    samp_order.Samp_results = '3'; // 部分合格
  } else {
    samp_order.Samp_results = '1'; // 兜底
  }
//  alert(samp_order.Samp_results)
}
// 根据仓库编码和产品编码查询库存信息
function StockSelect(warehouse_code, pro_code) {
  return axios.get("http://localhost:5181/api/Inv_Stock/GetinvStock", {
    params: {
      weahouse_code: warehouse_code,
      por_code: pro_code,
    },
    headers: {
      authorization: `Bearer ${localStorage.getItem('token')}`
    }
  }).then((res) => {
    return res.data;
  }).catch((res) => {
    console.log(res);
  })
}



/* 仓库变化 */
const handleWarehouseChange = val => {
  const w = warehouses.value.find(v => v.warehouse_code === val)
  samp_order.warehouse_name = w?.warehouse_name || ''
}
const handleSelectType = val => (samp_order.samp_type = val)

/* 添加 / 移除产品 */
function productAdd() {
    dialogTableVisible.value = true
    productFill();
}
// 移除选中的table控件数据
const productDel = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要移除的数据');
    return;
  }

  // 创建一个包含选中项的 stock_entry_no 和 pro_code 的数组
  const selectedEntries = selectedRows.value.map(item => ({
    stock_entry_no: item.stock_entry_no,
    pro_code: item.pro_code
  }));

  // 过滤掉被选中的项
  selectedData.value = selectedData.value.filter(item => {
    // 检查当前项的 stock_entry_no 和 pro_code 是否不在选中的数组中
    return !selectedEntries.some(
      selected =>
        selected.stock_entry_no === item.stock_entry_no &&
        selected.pro_code === item.pro_code
    );
  });

  if (selectedTable.value) {
    selectedTable.value.clearSelection();
  }
  selectedRows.value = [];
};


const updateTotals = () => {
  sampling_total_qty.value = 0;
  
  qualified_total_qty.value = 0;
  


};


/* 产品分页查询 */
// 分页查询产品库存信息
function productFill() {
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select_stock_All", {
        params: {
        weahouse_code: samp_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        productData.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

const productCount = () => {
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select__stock_Count", {
        params: {
        weahouse_code: samp_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        pageCount.value = result.data || 0
    }).catch((err) => {
        console.error(err);
    });
};

const productSearch = () => { productFill(); productCount() }
const productReset  = () => { productcode.value = ''; dict_code.value = '0'; productFill(); productCount() }

const handleSelectionChange = val => selectedProducts.value = val
const handleSelectedChange  = val => selectedRows.value = val


const isDisabled = (row) => {
  return !selectedData.value.some(
    item => item.pro_code === row.pro_code && item.stock_entry_no === row.stock_entry_no
  );
};

const handleConfirmSelection = () => {
  selectedData.value = [...selectedData.value, ...selectedProducts.value.map(item => ({
    ...item,
    samp_numder: 0,
    prodInfo_totnum_qify: 0,
    prodInfo_Sampling_results: '1'
  }))]
  dialogTableVisible.value = false
  multipleTableRef.value.clearSelection()
}

//修改
const handleUpdate = async () => {
  const valid = await ruleFormRef.value.validate().catch(() => false)
  if (!valid) return ElMessage.warning('请完善必填项')
  // 更新修改人
  samp_order.update_by = localStorage.getItem('userLName')
  samp_order.update_time = dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')


  //判断抽检结果
  calcResult();



  //明细表
  const detailList = selectedData.value.map(item => ({
    prodInfo_id: item.prodInfo_id || 0,
    samp_id: samp_order.samp_id,
    pro_name: item.stock_name,
    pro_code: item.pro_code,
    pro_brand: item.pro_brand,
    pro_model: item.stock_model,
    unitmeas_id: String(item.dict_code),
    samp_numder: Number(item.samp_numder),
    prodInfo_totnum_qify: Number(item.prodInfo_totnum_qify),
    prodInfo_totnum_uqual: Number(item.samp_numder) - Number(item.prodInfo_totnum_qify),
    prodInfo_Sampling_results: item.prodInfo_Sampling_results,
    warehouse_code: samp_order.warehouse_code,
    stock_entry_no: item.stock_entry_no,
  }))

//发送更新请求
  console.log(detailList)  


  const response = await axios.put("http://localhost:5181/api/Inv_Samp/Inv_Smap_Update",{
    inv_SmapUpdateMainDto:{
      samp_id: samp_order.samp_id,
      samp_code: samp_order.samp_code,
      samp_type: samp_order.samp_type,
      samp_inspector: samp_order.samp_inspector,
      samp_startdate: samp_order.samp_startdate,
      warehouse_code: samp_order.warehouse_code,
      warehouse_name: samp_order.warehouse_name,
      prodInfo_Sampling_results: samp_order.prodInfo_Sampling_results,
      update_by:samp_order.update_by,
      update_time:samp_order.update_time,
      del_flag: samp_order.del_flag,
      Samp_results: samp_order.Samp_results,
    },
    inv_ProdInfos: detailList


  },
  {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
  })
  if (response.data > 0) {
    ElMessage.success("抽检单修改成功");
    selectedData.value = [];
    handleClose();
    //清空路由的值
    warehouseStore.samp_code="";
  } else {
    ElMessage.error("修改失败");
  }
}

const handleClose = () => router.push('/main/Inv/InvSamp')



function handleSizeChange(val) {
  pageSize.value = val;
  productFill();
}

function handleCurrentChange(val) {
  currentPage.value = val;
  productFill();
}






function getMeasure() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        measureOptios.value = result.data
        measureOptios.value = [{
            dict_value: "0", dict_label: "请选择单位"
        }, ...result.data]
    }).catch((err) => {
        console.info(err)
    });
}
// 查询仓库信息
function getWarehouses() {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBy_Selectpd", {
        headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
    }).then((res) => {
        warehouses.value = res.data || [];
    }).catch((res) => {
        console.log(res);
    });
}




function getClassify() {
  axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
    params: {
      dict_type: "inv_samp"
    }, headers: {
      authorization: `Bearer ${localStorage.getItem('token')}`
    }
  }).then((result) => {
    options.value = result.data
  }).catch((err) => {
    console.info(err)
  });
}

function measure_samp_type(row) {
  if (!row) return "无";
  const type = options.value.find((item) => item.dict_value == row);
  return type ? type.dict_label : "无";
}


// 根据计量单位id返回计量单位名称
function measureValue(row) {
    if (!row) return "无";
    const unit = measureOptios.value.find((item) => item.dict_value == row);
    return unit ? unit.dict_label : "无";
}
/* ---------- 10. 生命周期 ---------- */
onMounted(() => {
  loadEditData()
  getMeasure()
  getWarehouses()

  getClassify()
})
</script>

<style scoped>
.inventory-edit-form{padding:20px;background:#fff;}
.section{margin-bottom:30px;border:1px solid #ebeef5;border-radius:4px;padding:20px;box-shadow:0 2px 12px rgba(0,0,0,.08);}
.section-title{font-size:16px;font-weight:bold;margin-bottom:15px;}
.button-group{display:flex;justify-content:flex-end;margin-top:20px;gap:10px;}
</style>